package com.ktjiaoyu.controller;

import com.alibaba.fastjson2.JSON;
import com.ktjiaoyu.entity.StorageRecord;
import com.ktjiaoyu.entity.Supplier;
import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SupplierService;
import com.ktjiaoyu.service.UploadService;
import com.ktjiaoyu.service.impl.SysUserServiceImpl;
import com.ktjiaoyu.utils.Constants;
import com.ktjiaoyu.utils.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/main/supplier")
public class SupplierController extends BaseController{
    private static final Logger LOGGER= LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SupplierService supplierService;

    @RequestMapping(value = "/page",produces = "application/json;charset=UTF-8")
    public String page(Model model, Supplier condition,
                       @RequestParam(value = "pageNo",defaultValue = "1")Integer pageNo,
                       @RequestParam(value = "pageSize",defaultValue = "5")Integer pageSize){
        Page<Supplier> page=null;
        try {
            page=supplierService.findPage(condition,pageNo,pageSize);

            model.addAttribute("pageInfo",page);
            model.addAttribute("condition",condition);
        }catch (Exception e){
            LOGGER.error("SupplierController中的page方法执行发生错误。",e);
            throw new RuntimeException(e);
        }
        return "supplier/page";
    }

    @GetMapping("/save")
    public String toSave(Model model){
        try {
            model.addAttribute("supplier",new Supplier());
        }catch (Exception e){
            LOGGER.error("SupplierController中的page方法执行发生错误。",e);
            throw new RuntimeException(e);
        }
        return "supplier/save";
    }

    @Autowired
    @Qualifier("toLocalUploadService")
    private UploadService uploadService;

    @PostMapping("/save")
    public String doSave(Supplier supplier, @RequestParam("bizPic") MultipartFile bizPic){
        String[] allowImageExt={"jpg","jpeg","png","gif","bmp"};

        try {
            if (bizPic != null){
                String bizPicPath= uploadService.uploadFile(bizPic,allowImageExt);
                supplier.setBizPicPath(bizPicPath);
            }

            SysUser loginUser=session(Constants.SESSION_USER);
            if ((supplier.getId()==null)){
                supplier.setCreatedUserId(loginUser.getId());
                supplier.setCreatedTime(new Date());
            }else {
                supplier.setUpdatedUserId(loginUser.getId());
                supplier.setUpdatedTime(new Date());
            }

            boolean ok=supplierService.saveOrUpdate(supplier);
            if (ok){
                if (supplier.getId()==null){
                    return redirect("/main/supplier/page");
                }else {
                    return "/supplier/view";
                }
            }
        }catch (Exception e){
            LOGGER.error("SupplierController中的doSave方法执行发生错误",e);
            throw new RuntimeException(e);
        }
        return "supplier/save";
    }

    @GetMapping("/view/{id}")
    public String view(@PathVariable("id") Long id, Model model){
        Supplier supplier=null;
        try {
            supplier=supplierService.findById(id);
            model.addAttribute("supplier",supplier);
        }catch (Exception e){
            LOGGER.error("SupplierController中的view方法执行发生错误",e);
            throw new RuntimeException(e);
        }

        return "supplier/view";
    }

    @ResponseBody
    @GetMapping("/supCodeExist")
    public String supCodeExist(@RequestParam("supCode") String supCode){
        LOGGER.info("检查编号supCode={}的供应商是否存在",supCode);
        HashMap<String,Object> resultMap=new HashMap<String,Object>();
        if (StringUtils.isEmpty(supCode)){
            resultMap.put("exist",0);
        }else {
            try {
                Supplier supplier=supplierService.findBySupCode(supCode);
                if (null!=supplier){
                    resultMap.put("exist",1);
                }else {
                    resultMap.put("exist",0);
                }
            }catch (Exception e){
                LOGGER.error("SupplierController中的supCodeExist方法执行发生错误。",e);
                resultMap.put("error","出现异常，请联系管理员处理");
            }
        }
        return JSON.toJSONString(resultMap);
    }

    @GetMapping(value = "/{id}/view",produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map ajaxView(@PathVariable("id") Long id){
        HashMap<String,Object> resultMap=new HashMap<String,Object>();
        Supplier info=null;
        try {
            info=supplierService.findById(id);
            if(info!=null){
                resultMap.put("code",200);
                resultMap.put("data",info);
            }else{
                resultMap.put("code",500);
            }
        }catch (Exception e){
            LOGGER.error("SupplierController中的ajaxView方法执行错误。",e);
            resultMap.put("code",500);
        }
        return resultMap;
    }

    @GetMapping("/edit")
    public String toEdit(@RequestParam("id") Long id,Model model){
        Supplier supplier=null;
        try {
            supplier=supplierService.findById(id);
            model.addAttribute("supplier",supplier);
        }catch (Exception e){
            LOGGER.error("SupplierController中的toEdit方法执行发生错误",e);
            throw new RuntimeException(e);
        }
        return "supplier/save";
    }

    @DeleteMapping( "/del/{id}")
    @ResponseBody
    public String del(@PathVariable("id") Long id){
        try {
            int count=supplierService.deleteById(id);
            return ajaxResult();
        }catch (Exception e){
            LOGGER.error("SupplierController中的del方法执行发生错误",e);
            throw new RuntimeException(e);
        }
    }
}
